//
//  PhotoBrowserViewController.swift
//  XinLangWeiBo
//
//  Created by mac on 15/11/18.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import SVProgressHUD
/// 可重用标识符号
private let PhotoBrowserViewCellId = "PhotoBrowserViewCellId"

class PhotoBrowserViewController: UIViewController {

    /// 图像 URL 数组
    var urls: [NSURL]
    /// 选中照片索引
    var selectedIndexPath: NSIndexPath

    // MARK: - 监听方法
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 保存照片
    @objc private func save() {
        print("保存照片")
        //1 拿到图片
        let cell = collectionView.visibleCells()[0] as! PhotoBrowserCell
       
        guard let image = cell.imageView.image else {
            return
        }
        
        
        //2 保存图片
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
        //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;

    
        
    }
  @objc private func image(image: UIImage, didFinishSavingWithError error: NSError?,contextInfo: AnyObject?) {
    
    let message = (error == nil) ? "保存层共" : "保存失败"
    
    SVProgressHUD.showInfoWithStatus(message)
    
        }
    
    //  MARK: -构造函数
    init(urls: [NSURL], IndexPath: NSIndexPath) {
        
        self.urls = urls
        self.selectedIndexPath = IndexPath
        
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func loadView() {
        //1 设置跟视图
        var rect = UIScreen.mainScreen().bounds
        rect.size.width += 20
        view = UIView(frame: rect)
        
        //2 设置界面
        setupUI()
    }
    
    // 是视图加载完成被调用，loadView 执行完毕被执行
    // 主要做数据加载，或者其他处理
    // 但是：目前市场上很多程序，没有实现 loadView，所有建立子控件的代码都在 viewDidLoad 中
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 让 collectionView 滚动到指定位置
        collectionView.scrollToItemAtIndexPath(selectedIndexPath, atScrollPosition: .CenteredHorizontally, animated: false)
        
    }

    
    
    // MARK: - 懒加载控件
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: PhotoBrowserViewLayout())
    
    /// 关闭按钮
    private lazy var closeButton: UIButton = UIButton(title: "关闭", fontSize: 14, color: UIColor.whiteColor(), imageName: nil, backColor: UIColor.darkGrayColor())
    /// 保存按钮
    private lazy var saveButton: UIButton = UIButton(title: "保存", fontSize: 14, color: UIColor.whiteColor(), imageName: nil, backColor: UIColor.darkGrayColor())

// MAKE: - 自定义流水布局
    private class PhotoBrowserViewLayout: UICollectionViewFlowLayout {
        
        private override func prepareLayout() {
            
            super.prepareLayout()
            
            itemSize = collectionView!.bounds.size
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            
            scrollDirection = .Horizontal
            
            collectionView?.pagingEnabled = true
            collectionView?.bounces = false
            
            
            collectionView?.showsHorizontalScrollIndicator = false
        }
        
    }
}


// MARK: - 设置 UI
private extension PhotoBrowserViewController {
    
    private func setupUI() {
        // 1. 添加控件
        view.addSubview(collectionView)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        
        // 2. 设置布局
        collectionView.frame = view.bounds
        
        closeButton.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.left.equalTo(view.snp_left).offset(8)
            make.size.equalTo(CGSize(width: 100, height: 36))
        }
        saveButton.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.right.equalTo(view.snp_right).offset(-28)
            make.size.equalTo(CGSize(width: 100, height: 36))
        }
        
        // 3. 监听方法
        closeButton.addTarget(self, action: "close", forControlEvents: .TouchUpInside)
        saveButton.addTarget(self, action: "save", forControlEvents: .TouchUpInside)
    
        // 4. 准备控件
        prepareCollectionView()
    }
    
    /// 准备 CollectionView
    private func prepareCollectionView() {
        // 1. 设置数据源
        
        collectionView.dataSource = self
        
        // 2 注册可重用 cell
        collectionView.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: PhotoBrowserViewCellId)
        
    }
    
}


// MAKE - 数据源方法
extension  PhotoBrowserViewController: UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoBrowserViewCellId, forIndexPath: indexPath) as! PhotoBrowserCell
        
         
        cell.imageURL = urls[indexPath.item]
        //cell.backgroundColor = UIColor.randomColor()
        
        cell.photoDelegate = self
        return cell
    }
    
}

// MARK: - PhotoBrowserCellDelegate
extension PhotoBrowserViewController: PhotoBrowserCellDelegate {
    
    func photoBrowserCellDidTapImage() {
        close()
    }
}
